package com.qlhx.service.impl;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.qlhx.common.model.Result;
import com.qlhx.common.util.DateUtil;
import com.qlhx.common.util.IConfig;
import com.qlhx.core.HTTP;
import com.qlhx.dao.BaseMemberMapper;
import com.qlhx.dao.BaseVisitorMapper;
import com.qlhx.model.*;
import com.qlhx.mybatis.BaseMybatisDao;
import com.qlhx.mybatis.page.Pagination;
import com.qlhx.service.BaseMiddleService;
import com.qlhx.util.Constant;
import com.qlhx.wechat.common.util.HardWareUtils;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import com.qlhx.common.util.CommonUtil;
import com.qlhx.common.util.GenericCodeUtils;
import com.qlhx.dao.BaseAccessRecordMapper;
import com.qlhx.service.AccessRecordService;
import org.springframework.web.client.RestTemplate;

@Service
public class AccessRecordServiceImpl extends BaseMybatisDao<BaseAccessRecordMapper> implements AccessRecordService {

    Logger logger  = LoggerFactory.getLogger(AccessRecordServiceImpl.class);

	@Autowired
    BaseAccessRecordMapper baseAccessRecordMapper;
	
	@Autowired
    BaseVisitorMapper baseVisitorMapper;


	@Autowired
    BaseMemberMapper baseMemberMapper;

	@Autowired
    BaseMiddleService baseMiddleService;
    @Autowired
    private RestTemplate rest;

	//#登记完成是否发送推送信息 0 否 1 是
    //issendmsgafterregister=1
    //#微信上报的url
    //data.upload.url=http://wx.xjucan.com/AIcloudHead/sync
    //#公司编号
    //companycode=C100000_1000

    private String issendmsgafterregister = IConfig.get("issendmsgafterregister");

    private String uploadurl = IConfig.get("data.upload.url");

    private String companycode = IConfig.get("companycode");
	
	@Override
	public Pagination<BaseAccessRecord> selectAccessRecord(Map<String, Object> modelMap, Integer pageNo, Integer pageSize) {
		return super.findPage(modelMap, pageNo, pageSize);
	}
	@Override
	public int insertSelective(BaseAccessRecord record) {
		return baseAccessRecordMapper.insertSelective(record);
	}

	@Override
	public Result<Map<String, Object>> SaveAccessRecord(BaseAccessRecord record) throws Exception {
		Result<Map<String, Object>> result = new Result<Map<String, Object>>();

		// 访客记录必要参数检查
		if (StringUtils.isBlank(record.getReasons())) {
			record.setReasons("开会");
		}
		if (checkccessRecordParam(result, record) && checkIDInfo(result, record.getVisitor())) {
			record.setUid(Integer.parseInt(record.getUser().getId() + ""));
			// 更新访客信息（新访客添加，已添加访客更新）
			BaseVisitor visitor = record.getVisitor();
			BaseVisitor visitorTemp = baseVisitorMapper.selectByIdNum(record.getVisitor().getIdnum());
			
			// 获取需要注册的图片
			String visitorPhoto = visitor.getPhoto();
			if(StringUtils.isNotBlank(visitorPhoto))
			{
				String sitePhotoPath = CommonUtil.saveImg(visitorPhoto, Constant.IMG_PATH, "visitorPhoto", record.getVisitor().getIdnum());
				visitor.setPhoto(sitePhotoPath);
			}
			if (visitorTemp == null) {
				baseVisitorMapper.insertSelective(visitor);
			} else {
				visitor.setId(visitorTemp.getId());
				baseVisitorMapper.updateByPrimaryKeySelective(visitor);
			}
			record.setType(0);
			record.setVid(visitor.getId());
			// 添加主访客记录信息
			record.setStatus(0);
			// 获取需要注册的图片
			String sitePhoto = record.getSitephoto();
			if(StringUtils.isNotBlank(sitePhoto))
			{
				String sitePhotoPath = CommonUtil.saveImg(sitePhoto, Constant.IMG_PATH, "sitePhoto", record.getVisitor().getIdnum());
				record.setSitephoto(sitePhotoPath);
			}
			
			if (baseAccessRecordMapper.insertSelective(record) > 0) {
				String code = GenericCodeUtils.GetRandomPre() + GenericCodeUtils.autoGenericCode(record.getId(), 5);
				if (record.getCardnum() == null || "".equals(record.getCardnum())) {
                    record.setCardnum(code);
                    //默认生成的卡号type 0
                    record.setCardtype(2);
                } else {
                    //发卡
                    record.setCardtype(0);
                }
				baseAccessRecordMapper.updateByPrimaryKey(record);
                Map<String, Object> m = new HashMap<String, Object>();
                m.put("id", record.getId());
                m.put("vid", record.getVisitor().getId());
                m.put("rCode", baseAccessRecordMapper.selectByPrimaryKey(record.getId()).getCardnum());
                result.setContent(m);
            }

            /**
             * 这里是虚假数据为演示所用
             */
            BaseMiddle baseMiddle = new BaseMiddle();
            baseMiddle.setGroupId(1);
            baseMiddle.setPersonId(visitor.getId());
            baseMiddle.setType(2);
            baseMiddleService.insert(baseMiddle);

			//像微信端发送访客访问信息
            SendMsg(record,visitor.getPhone(),visitor.getName());
		    //SendMsg1(record,uploadurl,companycode);
		}
		return result;
	}
    /**
     *
     * @param record 访客记录对象
     * @throws Exception
     */
    private void  SendMsg1 (BaseAccessRecord record,String uploadurl,String companycode){
        if ("1".equals(issendmsgafterregister)) {
            BaseAccessRecord  recordtemp= baseAccessRecordMapper.selectByPrimaryKey(record.getId());
            if(recordtemp.getType()==1)
            {
                //微信预约数据不上传审批
                return;
            }
            BaseMember user = baseMemberMapper.selectByPrimaryKey(Long.parseLong("" + record.getUid()));
            if (user == null) {
                logger.error("访客登记发送推送信息，根据被访人查询员工信息为空 员工id：" + record.getUid());
            }
            UWxVisitorRegisterParam uWxVisitorRegisterParam = new UWxVisitorRegisterParam();
            uWxVisitorRegisterParam.setAccessId(record.getId());
            uWxVisitorRegisterParam.setAreaCode(companycode);
            uWxVisitorRegisterParam.setCardNum(record.getCardnum());
            uWxVisitorRegisterParam.setCreateTime(DateUtil.dateToString(record.getCreatetime(),"yyyy-MM-dd HH:mm:ss"));
            if (user != null) {
                uWxVisitorRegisterParam.setEmployeeName(user.getNickname());
                uWxVisitorRegisterParam.setEmployeePhone(user.getPhone());
            }
            uWxVisitorRegisterParam.setEndTime(record.getEndtime());
            uWxVisitorRegisterParam.setReason(record.getReasons());
            uWxVisitorRegisterParam.setStartTime(record.getStarttime());
            uWxVisitorRegisterParam.setUnit(record.getUnit());
            uWxVisitorRegisterParam.setVisitorIdnum(record.getVisitor().getIdnum());
            uWxVisitorRegisterParam.setVisitorPhone(record.getVisitor().getPhone());
            uWxVisitorRegisterParam.setVisitorName(record.getVisitor().getName());
            String resultjson = HTTP.post(uploadurl + "/visitorRegSendSms?token=" + HardWareUtils.GetLocalAuthCode
             () + "&areaCode=" + companycode, JSON.toJSONString(uWxVisitorRegisterParam));
            com.alibaba.fastjson.JSONObject result = JSON.parseObject(resultjson);
            if (null != result) {
                Object code = result.get("code");
                if (code != null && "1000".equals(code.toString())) {
                } else {
                    Object msg = result.get("msg");
                    throw new RuntimeException("登记完成发送推送消息异常" + msg);
                }
            }
        }else {
            logger.info("没有开启登记完成发消息");
        }
    }
    private void SendMsg(BaseAccessRecord record,String phone,String name ) throws Exception {
        Map<String,Object> map = new HashMap<>();
        map.put("reson",record.getReasons());
        map.put("uid",record.getUid());
        map.put("starttime",record.getStarttime());
        map.put("endtime",record.getEndtime());
        map.put("unit",record.getUnit());
        map.put("carNum","");
        map.put("name",name);
        map.put("utel",phone);
        String uploadurl = IConfig.get("data.upload.url");
        String companycode = IConfig.get("companycode");
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(type);
        headers.set("areaCode",companycode);
        JSONObject jsonObj = JSONObject.fromObject(map);
        HttpEntity<String> formEntity = new HttpEntity<>(jsonObj.toString(), headers);
        String result = rest.postForObject(uploadurl+"/wxapply/personalApply", formEntity, String.class);
        logger.info(result);


        //{"reson":"","uid":1681,"starttime":"2019/07/28 14:10:00","endtime":"2019/07/28 18:00:00","unit":"不知道","carNum":""}

    }

	
	   private boolean checkccessRecordParam(Result result, BaseAccessRecord record)
			throws Exception {
		// TODO Auto-generated method stub
		if (record == null || record.getUser().getId() == null || record.getUser().getId() == 0) {
			result.setCode(1001);
			result.setMsg("被访人不存在！");
			return false;
		} else if (record.getStarttime() == null) {
			result.setCode(1001);
			result.setMsg("访问开始时间不存在！");
			return false;
		} else if (record.getEndtime() == null) {
			result.setCode(1001);
			result.setMsg("访问结束时间不存在！");
			return false;
		}
		return true;
	}
	   
	   private boolean checkIDInfo(Result result, BaseVisitor visitor){
	        if (visitor == null) {
	            result.setCode(1001);
	            result.setMsg("访客信息不存在！");
	            return false;
	        } else if (visitor.getIdnum() == null) {
	            result.setCode(1001);
	            result.setMsg("访客身份证号不存在！");
	            return false;
	        } else if (visitor.getName() == null) {
	            result.setCode(1001);
	            result.setMsg("访客姓名不存在！");
	            return false;
	        } else if (visitor.getSex() == null) {
	            visitor.setSex("男");
	        }
	        return true;
	    }

	@Override
	public Result<Map<String, Object>> addEntourage(BaseAccessRecord record) throws Exception {
		Result<Map<String, Object>> result = new Result<Map<String, Object>>();

		BaseAccessRecord ac = baseAccessRecordMapper.selectByPrimaryKey(record.getParentid());
		if (record.getParentid() == null || ac == null) 
		{
			result.setCode(1001);
			result.setMsg("主访记录ID不存在！");
			return result;
		}
		// 访客记录必要参数检查
		if (StringUtils.isBlank(record.getReasons())) {
			record.setReasons("开会");
		}
		if (checkccessRecordParam(result, record) && checkIDInfo(result, record.getVisitor())) {
			record.setUid(Integer.parseInt(record.getUser().getId() + ""));
			// 更新访客信息（新访客添加，已添加访客更新）
			BaseVisitor visitor = record.getVisitor();
			BaseVisitor visitorTemp = baseVisitorMapper.selectByIdNum(record.getVisitor().getIdnum());
			if (visitor == null) {
				baseVisitorMapper.insertSelective(visitor);
			} else {
				visitor.setId(visitorTemp.getId());
				baseVisitorMapper.updateByPrimaryKeySelective(visitor);
			}
			record.setVid(visitor.getId());
			// 添加主访客记录信息
			record.setStatus(0);

			// 获取需要注册的图片
			String photo = record.getSitephoto();
			if (baseAccessRecordMapper.insertSelective(record) > 0) {
				String code = GenericCodeUtils.GetRandomPre() + GenericCodeUtils.autoGenericCode(record.getId(), 5);
				if (record.getCardnum() == null || "".equals(record.getCardnum())) {
                    record.setCardnum(code);
                    //默认生成的卡号type 0
                    record.setCardtype(2);
                } else {
                    //发卡
                    record.setCardtype(0);
                }
				baseAccessRecordMapper.updateByPrimaryKey(record);
				Map<String, Object> m = new HashMap<String, Object>();
				m.put("id", record.getId());
				m.put("vid", record.getVisitor().getId());
				m.put("rCode", baseAccessRecordMapper.selectByPrimaryKey(record.getId()).getCardnum());
				result.setContent(m);
				// RegisterFace(record, photo);
			}
		}
		return result;
	}

	@Override
	public Integer findAccessRecordPageCount(BaseAccessRecord record) throws Exception {
		return baseAccessRecordMapper.findAccessRecordPageCount(record);
	}

	@Override
	public List<BaseAccessRecord> findAccessRecord(BaseAccessRecord record) throws Exception {
		return baseAccessRecordMapper.findAccessRecord(record);
	}

	@Override
	public BaseAccessRecord findAccessRecordByCardNum(String cardNum) {
		return baseAccessRecordMapper.findAccessRecordByCardNum(cardNum);
	}

	@Override
	public int updateByPrimaryKeySelective(BaseAccessRecord record) {
		return baseAccessRecordMapper.updateByPrimaryKeySelective(record);
	}

}
